﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RATSharpW7.ViewModel;
using System.Windows.Navigation;
using RATSharp.Model;
using Microsoft.Phone.Shell;
using Coding4Fun.Toolkit.Controls;

namespace RATSharpW7.View
{
    /// <summary>
    /// Edit reservation activity. It is almost the same as 
    /// CreateReservationActivity, but there are numberofWeeks and 
    /// periodical toggles disabled and it allows to delete reservation and
    /// shows periodical reservation edit screen.
    /// </summary>
    public partial class EditReservation : PhoneApplicationPage
    {

        bool isNewPageInstance = false;
        EditPeriodViewModel model;
        public EditReservation()
        {
            InitializeComponent();
            isNewPageInstance = true;
        }

        private void sinceDatePicker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            DateTimePickerBase picker = sender as DateTimePickerBase;

            if (e.OldDateTime.HasValue && e.NewDateTime.HasValue && e.OldDateTime.Value != e.NewDateTime.Value)
            {
                string message;
                if (!model.validateDateBeforeNow(e.NewDateTime.Value, out message))
                {
                    ViewUtils.reportError(message);
                    picker.ValueChanged -= sinceDatePicker_ValueChanged;
                    picker.Value = e.OldDateTime.Value;
                    picker.ValueChanged += sinceDatePicker_ValueChanged;
                    return;
                }
                model.DataSource.FromDate = e.NewDateTime.Value;
            }
        }

        private void toDatePicker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            DateTimePickerBase picker = sender as DateTimePickerBase;

            if (e.OldDateTime.HasValue && e.NewDateTime.HasValue && e.OldDateTime.Value != e.NewDateTime.Value)
            {
                string message;
                if (!model.validateDateBeforeNow(e.NewDateTime.Value, out message))
                {
                    ViewUtils.reportError(message);
                    // quite dirty hack in here. But Binding isnt helpful here - we need to validate
                    // dates knowing what the old datetime value was. Only way how to archieve that is this listener.
                    //We cant do that on model level - periods sure can be placed in the past, this validation
                    //is only related to create/edit form
                    //Solution would be use OneWay binding, but it is not working with trirdparty pickers!
                    //(see http://jesperbjerre.wordpress.com/2012/08/09/wp-datepicker-oneway-databinding-problem/)
                    //So we need to stop somewhere in updating  - and deregister ourselves is the
                    //way how to archieve that
                    picker.ValueChanged -= toDatePicker_ValueChanged;
                    picker.Value = e.OldDateTime.Value;
                    picker.ValueChanged += toDatePicker_ValueChanged;
                    return;
                }
                model.DataSource.ToDate = e.NewDateTime.Value;
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode !=
                  System.Windows.Navigation.NavigationMode.Back)
            {
                State["EditPeriodViewModel"] = model;
            }
        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode ==
                 System.Windows.Navigation.NavigationMode.Back)
            {
                if (ReservationPeriods.ModelChanged)
                {
                    NavigationService.GoBack();
                }
            }
            else
            {

                if (isNewPageInstance)
                {
                    if (model == null)
                    {
                        if (State.ContainsKey("EditPeriodViewModel"))
                        {
                            model = State["EditPeriodViewModel"]
                                               as EditPeriodViewModel;
                        }
                        else
                        {
                            period period = NavigationContext.GetData<period>();

                            model = new EditPeriodViewModel(period);
                        }
                    }
                    DataContext = model;
                }
                isNewPageInstance = false;
                initActionBar();
            }
        }


        private void reservationSubmittedHandler(object sender, ModifyReservationEventArgs e)
        {
            if (!e.succesfull)
            {
                ViewUtils.reportError(e.message);
            }
            else
            {
                if (NavigationService.CanGoBack)
                {
                    NavigationService.GoBack();
                }
            }
        }

        private void submitReservationButton_Click(object sender, EventArgs e)
        {


            model.submitChanges(new EventHandler<ModifyReservationEventArgs>(reservationSubmittedHandler));
        }

        private void multipleReservationButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate("View", typeof(ReservationPeriods), model.DataSource);
        }

        private void deleteReservationButton_Click(object sender, EventArgs e)
        {

            var messagePrompt = new MessagePrompt
            {
                Title = Application.Current.Resources["ReallyDeleteReservationPopupLabel"] as string,
                IsAppBarVisible = false,
                IsCancelVisible = true
            };
            messagePrompt.Completed += (s1, e1) =>
            {
                if(e1.PopUpResult == PopUpResult.Ok) 
                {
                    model.deleteReservation(new EventHandler<ModifyReservationEventArgs>(reservationSubmittedHandler));
                }
            };
            messagePrompt.Show();
        }

        private void initActionBar()
        {
            this.ApplicationBar = new ApplicationBar();
            this.ApplicationBar.IsVisible = true;
            this.ApplicationBar.Opacity = 1;

            ApplicationBarIconButton submitReservationButton = new ApplicationBarIconButton(new Uri("/Images/submit.png", UriKind.RelativeOrAbsolute));
            submitReservationButton.Text = Application.Current.Resources["EditReservationLabel"] as string;
            submitReservationButton.Click += new EventHandler(submitReservationButton_Click);
            this.ApplicationBar.Buttons.Add(submitReservationButton);

            ApplicationBarIconButton deleteReservationButton = new ApplicationBarIconButton(new Uri("/Images/delete.png", UriKind.RelativeOrAbsolute));
            deleteReservationButton.Text = Application.Current.Resources["DeleteReservationLabel"] as string;
            deleteReservationButton.Click += new EventHandler(deleteReservationButton_Click);
            this.ApplicationBar.Buttons.Add(deleteReservationButton);

            if (model.DataSource.reservation.Periodical)
            {
                ApplicationBarIconButton multipleReservationButton = new ApplicationBarIconButton(new Uri("/Images/multiple.png", UriKind.RelativeOrAbsolute));
                multipleReservationButton.Text = Application.Current.Resources["EditMultipleReservationLabel"] as string;
                multipleReservationButton.Click += new EventHandler(multipleReservationButton_Click);
                this.ApplicationBar.Buttons.Add(multipleReservationButton);
            }

            ApplicationBarMenuItem viewObjectItem = new ApplicationBarMenuItem();
            viewObjectItem.Text = Application.Current.Resources["ViewObjectLabel"] as string;
            viewObjectItem.Click += new EventHandler(viewObjectButton_Click);
            this.ApplicationBar.MenuItems.Add(viewObjectItem);
        }

        private void viewObjectButton_Click(object sender, EventArgs e)
        {
            model.loadObject(model.DataSource.reservation.objectId, new EventHandler<PeriodViewModel.LoadObjectEventArgs>(objectLoaderHandler));
        }

        private void objectLoaderHandler(object sender, PeriodViewModel.LoadObjectEventArgs e)
        {
            if (e.succesfull)
            {
                NavigationService.Navigate("View", typeof(SimpleObjectProfile), e.obj);
            }
        }

    }
}